import axios from 'axios';

/** 取消重复请求的拦截器 */
function generateReqKey(config) {
  const { method, url, params, data } = config;
  if (!url) return ""
  let list = url.split('/')
  let str = list.slice(list.length - 3).join('/')
  return [method, str].join(' & ');
}

const pendingRequest = {};
function addPendingRequest(config) {
  const requestKey = generateReqKey(config);

  config.cancelToken = new axios.CancelToken((cancel) => {
    if (!pendingRequest[requestKey]) {
      pendingRequest[requestKey] = cancel;
    }
  });
}

function removePendingRequest(config) {
  const requestKey = generateReqKey(config);
  if (pendingRequest[requestKey]) {
    const cancelToken = pendingRequest[requestKey];
    cancelToken(requestKey);
    delete pendingRequest[requestKey];
  }
}

export default function repetitiveInterceptor({request, response}) {
  request.use(
    function(config) {
      removePendingRequest(config); // 检查是否存在重复请求，若存在则取消已发的请求
      addPendingRequest(config); // 把当前请求信息添加到pendingRequest对象中
      return config;
    },
    (error) => {
      return Promise.reject(error);
    }
  );

  response.use(
    (response) => {
      removePendingRequest(response.config); // 从pendingRequest对象中移除请求
      return response;
    },
    (error) => {
      removePendingRequest(error.config || {}); // 从pendingRequest对象中移除请求

      return Promise.reject(error);
    }
  );
}
